/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.milib.tools {
	import com.googlecode.milib.base.MLBaseClass;
	import com.googlecode.milib.data.WeakReferencesCollection;
	import com.googlecode.milib.util.MLArrayUtil;

	import flash.display.InteractiveObject;
	import flash.events.FocusEvent;
	import flash.text.TextField;

	/**
	 * @author Marek Brun
	 */
	public class TabIndexGroup extends MLBaseClass {

		private var objs:WeakReferencesCollection;
		private var objects:Array;

		public function TabIndexGroup(objects:Array) {
			objs=new WeakReferencesCollection(objects);
			this.objects=objects;
			var i:uint;
			var loop:InteractiveObject;
			for(i=0;i<objects.length;i++){
				loop=objects[i];
				loop.tabEnabled=true;
				loop.addEventListener(FocusEvent.FOCUS_IN, onObjFocusIn, false, 0, true);				loop.addEventListener(FocusEvent.FOCUS_OUT, onObjFocusOut, false, 0, true);
			}
		}
		
//********************************************************************************************
//		events for TabIndexGroup
//********************************************************************************************
		protected function onObjFocusIn(event:FocusEvent):void {
			//var objects:Array=objs.toArray();
			var focused:InteractiveObject=InteractiveObject(event.target);
			var next:InteractiveObject=InteractiveObject(MLArrayUtil.getNextByValue(objects, focused));
			var i:uint;
			var loop:InteractiveObject;
			for(i=0;i<objects.length;i++){
				loop=objects[i];
				loop.tabIndex=99;
			}
			focused.tabIndex=100;
			next.tabIndex=101;
			if(focused is TextField){
				TextField(focused).scrollH=0;				TextField(focused).setSelection(TextField(focused).length, TextField(focused).length);
			}
		}
		
		protected function onObjFocusOut(event:FocusEvent):void {
			var focused:InteractiveObject=InteractiveObject(event.target);
			if(focused is TextField){
				TextField(focused).scrollH=0;
				TextField(focused).setSelection(TextField(focused).length, TextField(focused).length);
			}
		}
		
	}
}
